package com.itheima.servlet;

import com.itheima.utils.DownLoadUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(urlPatterns = "/downloadServlet2")
public class DownloadServlet2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");

        InputStream in = getServletContext().getResourceAsStream("/img/" + filename);

        //1. 获取浏览器版本信息
        String agent = request.getHeader("user-agent");

        //2. 根据浏览器版本信息,对中文文件名进行响应的编码
        filename = DownLoadUtils.getFileName(agent, filename); // 重新赋值

        response.setHeader("content-disposition", "attachment;filename=" + filename);

        ServletOutputStream out = response.getOutputStream();

        IOUtils.copy(in, out);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}